package com.coolcode.service.impl;

import com.coolcode.entity.Menu;
import com.coolcode.mapper.MenuMapper;
import com.coolcode.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.function.Function.identity;

@Service
public class MenuServiceImpl implements MenuService {

    private MenuMapper menuMapper;

    @Autowired
    public MenuServiceImpl(MenuMapper menuMapper) {
        this.menuMapper = menuMapper;
    }

    @Override
    public List<Menu> getAllMenu() {

        List<Menu> allMenuList = menuMapper.getAllMenu();

        final Map<Long, List<Menu>> parentId2Menu = allMenuList.stream()
                .collect(Collectors.groupingBy(menu -> menu.getParentId()));
        for (Menu menu : allMenuList) {
            List<Menu> menuList = parentId2Menu.get(menu.getId());
            if (menuList != null) {
                menu.getChildren().addAll(menuList);
            }
        }

        return allMenuList.stream().filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());
    }
}
